package com.sanri.tools.modules.mock.l7.websocket.server;

import com.sanri.tools.modules.core.service.SpringUtils;
import com.sanri.tools.modules.mock.l7.websocket.event.*;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomWebsocketServer extends WebSocketServer {

    @FunctionalInterface
    public interface OnStart{
        void start(CustomWebsocketServer websocketServer);
    }

    private OnStart startListener;

    public CustomWebsocketServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        WebsocketEvent websocketEvent = new ConnectWebsocketEvent(conn, handshake);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        WebsocketEvent websocketEvent = new CloseWebsocketEvent(conn, code,reason, remote);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        final WebsocketEvent websocketEvent = new MessageWebsocketEvent(conn, message);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        WebsocketEvent websocketEvent = new ErrorWebsocketEvent(conn, ex);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    /**
     * @param listener
     */
    public void start(OnStart listener){
        startListener = listener;
    }

    @Override
    public void onStart() {
        if (startListener != null) {
            startListener.start(this);
        }
    }
}
